package com.example.demo.service;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

import javax.imageio.ImageIO;

@Service
public class FileService {

    private final Path fileStorageLocation = Paths.get("/www/wwwroot/peanutPhotos");

    public String storeFile(MultipartFile file) throws IOException {
        String fileName = generateFileName(file);
        Path targetLocation = fileStorageLocation.resolve(fileName);
        Files.copy(file.getInputStream(), targetLocation);

        // 裁剪图片
        File croppedFile = cropImage(targetLocation.toFile());

        return croppedFile.getName();
    }

    private String generateFileName(MultipartFile file) {
        return UUID.randomUUID().toString() + "_" + file.getOriginalFilename();
    }

    private File cropImage(File inputFile) throws IOException {
        // 读取原始图片
        BufferedImage image = ImageIO.read(inputFile);

        // 计算裁剪区域的起始坐标和大小，使得裁剪为 960x960 的正方形
        int originalWidth = image.getWidth();
        int originalHeight = image.getHeight();

        int targetSize = 960; // 目标尺寸

        int x = Math.max(0, originalWidth / 2 - targetSize / 2); // 计算起始 x 坐标
        int y = Math.max(0, originalHeight / 2 - targetSize / 2); // 计算起始 y 坐标

        // 裁剪区域的实际大小（取最小值，确保不超出图片边界）
        int cropSize = Math.min(originalWidth - x, originalHeight - y);

        // 裁剪图片
        BufferedImage croppedImage = image.getSubimage(x, y, cropSize, cropSize);

        // 调整裁剪后的大小为 960x960
        BufferedImage resizedImage = new BufferedImage(targetSize, targetSize, BufferedImage.TYPE_INT_RGB);
        resizedImage.getGraphics().drawImage(croppedImage.getScaledInstance(targetSize, targetSize, BufferedImage.SCALE_SMOOTH), 0, 0, null);

        // 生成裁剪后的文件名
        String croppedFileName = "cropped_" + inputFile.getName();

        // 写出裁剪后的图片到指定位置
        File croppedFile = new File(fileStorageLocation.resolve(croppedFileName).toString());
        ImageIO.write(resizedImage, "jpg", croppedFile);

        return croppedFile;
    }
}
